package com.telit.firecommand.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.push.model.v20160801.PushResponse;
import com.telit.common.constant.*;
import com.telit.common.dto.SmsRealDto;
import com.telit.common.entity.DataReturn;
import com.telit.common.enums.ResultCode;
import com.telit.common.exception.ForestBaseException;
import com.telit.common.pojo.AliPushContentPojo;
import com.telit.common.pojo.AliPushMessagePojo;
import com.telit.common.util.*;
import com.telit.communicate.dto.SendMessageDTO;
import com.telit.communicate.feign.RemoteCommunicateService;
import com.telit.firecommand.constant.RedisKeyConstant;
import com.telit.firecommand.dao.*;
import com.telit.firecommand.dto.*;
import com.telit.firecommand.entity.*;
import com.telit.firecommand.facade.SmsPushUriPubFacadeService;
import com.telit.firecommand.facade.VoicePushFacadeService;
import com.telit.firecommand.listener.FireExcludeProp;
import com.telit.firecommand.service.*;
import com.telit.firecommand.vo.CameraVO;
import com.telit.upms.vo.MicroSysUserAllInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chencf
 * @description 火情管理实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class FireManagerServiceImpl implements FireManagerService {
    @Autowired
    private CommFireAlarmDao commFireAlarmDao;

    @Autowired
    private WebsocketPushMsgLogDao websocketPushMsgLogDao;

    @Autowired
    private FireReportSuperiorLogDao fireReportSuperiorLogDao;

    @Autowired
    private CommunicateRecordService communicateRecordService;

    @Autowired
    private BusinessTableDao businessTableDao;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RemoteCommunicateService communicateFeignClient;

    @Autowired
    private FireQueryService fireQueryService;

    @Autowired
    private GeoQueryService geoQueryService;

    @Autowired
    private WeatherService weatherService;

    @Autowired
    private FireWeatherInfoDao fireWeatherInfoDao;

    @Autowired
    private CommMsgCenterLogDao commMsgCenterLogDao;
    
    @Autowired
    private ICadPlotRoomService cadPlotRoomService;

//    @Autowired
//    private ICommFireOnemapService commFireOnemapService;

    @Autowired
    private FireAdminService fireAdminService;

//    @Autowired
//    private OperationFeignClient operationFeignClient;

    @Autowired
    private CameraInfoService cameraInfoService;

    @Autowired
    private SmsPushUriPubFacadeService smsPushUriPubFacadeService;

    @Autowired
    private MsgService msgService;

    @Autowired
    private GeoXzqhCunDao geoXzqhCunDao;

    @Autowired
    private VoicePushFacadeService voicePushFacadeService;

    @Autowired
    private FireDisposeService fireDisposeService;

    @Autowired
    private FireExcludeProp fireExcludeProp;

    @Autowired
    private FileUploadLogService fileUploadLogService;

    @Autowired
    private SysUserDAO sysUserDAO;

    @Value("${fire.limitDistance}")
    private String limitDistance;
    /*  @Value("${fire.excludeDistrict}")
      private String excludeDistrict;*/
    @Value("${weather.address}")
    private String address;

    @Value("${forest.enablePushFireSms}")
    private String enablePushFireSms;

    @Autowired
    private ICommFireOnemapService commFireOnemapService;

    /**
     * 此方法暂时废弃，先采用的是FireTriggerFacadeService中的addFire方法
     *
     * @param commFireAlarm
     * @param httpServletRequest
     *
     * @throws Exception
     */
    @Override
    public void addFire(CommFireAlarm commFireAlarm, HttpServletRequest httpServletRequest) throws Exception {
        //重复火情判断
        String fireSource = commFireAlarm.getResource();
        String longitude = commFireAlarm.getLongitude();
        String latitude = commFireAlarm.getLatitude();
        List<String> list = new ArrayList<>(5);
        if (commFireAlarm.getOriginFireId() == null) {
            switch (fireSource) {
                case "1"://飞手
                case "2"://护林员
                    list.add("1");
                    list.add("2");
                    this.verifySameFire(list, longitude, latitude);
                    break;
                //case "3"://视频监控
                case "4"://卫星
                case "5"://无人机
                    //case "8"://可见光
                    //case "9"://红外热成像
                    list.add("3");
                    list.add("4");
                    list.add("5");
                    list.add("8");
                    list.add("9");
                    this.verifySameFire(list, longitude, latitude);
                    break;
                case "6"://防火管理员
                case "7"://电话接警
                    list.add("6");
                    list.add("7");
                    this.verifySameFire(list, longitude, latitude);
                    break;
                default:
            }
        }
        //插入火情信息
      /*  if (commFireAlarm.getOriginFireId() != 0) {
            commFireAlarm.setHasDelete(1);
        } else {
            commFireAlarm.setHasDelete(0);
        }*/
        // 传入0标识 0，否则都是1
        //如果originFireId不是空，代表合并火情，目前也不作标识删除处理
       /* commFireAlarm.setHasDelete(
                NumberUtil.equals(Convert.toBigDecimal(commFireAlarm.getOriginFireId(), BigDecimal.ZERO), BigDecimal.ZERO) ? 0 : 1
        );*/

        if (commFireAlarm.getOriginFireId() != null && commFireAlarm.getOriginFireId() != 0 && "6".equals(commFireAlarm.getResource())) {
            commFireAlarm.setHasDelete(1);
        } else {
            commFireAlarm.setHasDelete(0);
        }
        //查询详细地址
        String detailAddress = commFireAlarm.getDetailAddress();
        if (StringUtils.isEmpty(detailAddress)) {
            if (longitude != null && latitude != null && !"0.0".equals(longitude) && !"0.0".equals(latitude)) {
                detailAddress = GaodeUtils.queryAddressByLaAndLo(commFireAlarm.getLongitude(), commFireAlarm.getLatitude());
                commFireAlarm.setDetailAddress(detailAddress);
            }
        }

        //查询行政区划
        String districtCode = commFireAlarm.getDistrictCode();
        if (StringUtils.isEmpty(districtCode)) {
            if (longitude != null && latitude != null && !"0.0".equals(longitude) && !"0.0".equals(latitude)) {
                GeoCunDTO geoCunDTO = geoXzqhCunDao.getDistrictByPoint(longitude, latitude);
                districtCode = geoCunDTO.getCun();
                commFireAlarm.setDistrictCode(districtCode);
            }
        }

        //插入火情数据
        commFireAlarmDao.insertSelective(commFireAlarm);
        //查询一张图数据并插入
        CommFireOnemap commFireOnemap = commFireOnemapService.findByPoint(commFireAlarm.getLongitude(),
                commFireAlarm.getLatitude());
        //对于不存在的经纬度抛出异常
       /* if (ObjectUtil.isNull(commFireOnemap)) {
            throw new ForestBaseException("传入的经纬度不在区划范围内！");
        }*/
        if (ObjectUtil.isNotEmpty(commFireOnemap)) {
            commFireOnemap.setFireId(commFireAlarm.getId());
            commFireOnemapService.add(commFireOnemap);
        }
        //插入天气信息
        try {
            this.insertWeatherInfo(commFireAlarm.getId());
        } catch (Exception e) {
            log.info("插入天气失败{}", e.getCause());
        }
        //判断电话接警的已有火情除外
        if (commFireAlarm.getOriginFireId() != null && commFireAlarm.getOriginFireId() != 0) {
            //插入业务主键表信息
            this.insertBusinessTable(commFireAlarm);
        }
        //delete=1时为合并已有火情，或者判别为误报的，不需要推送
        //orginId !=null时为合并已有火情，或者判别为误报的，不需要推送
        if ((commFireAlarm.getOriginFireId() == null || commFireAlarm.getOriginFireId() == 0) && !"3".equals(commFireAlarm.getFireJudgmentType())) {
            //推送给web端
            if ("3".equals(fireSource) || "8".equals(fireSource) || "9".equals(fireSource)) {

                //查询监控名称
                CameraVO commCameraInfo = cameraInfoService.info(commFireAlarm.getDeviceId().toString());
                //推送给安卓值守端
                String content = MessageFormat.format(NoticeTemplateConstants.CAMERA_PUSH_MANUAL_DUTY_CONTENT,
                        null == commCameraInfo.getCameraName() ? null : commCameraInfo.getCameraName(), detailAddress);
                String title = NoticeTemplateConstants.CAMERA_PUSH_MANUAL_DUTY_TITLE;

                List<SysUser> sysUsers = sysUserDAO.selectByCondition(null, null, null, true,
                        RoleCodeConstants.ROLE_CODE_MANUAL_DUTY_ID, null, null, Integer.MAX_VALUE, 0);
                if (CollectionUtil.isNotEmpty(sysUsers)) {
                    List<Long> ids = sysUsers.stream().map(SysUser::getId).collect(Collectors.toList());
                    List<String> forestkeeperIdList = Convert.toList(String.class, ids);
                    try {
                        final PushResponse pushResponse = AliyunPushMessageUtils.customizeAdvancedPush(
                                new AliPushMessagePojo(MsgConstants.TARGET_ACCOUNT, MsgConstants.PUSH_TYPE_MESSAGE,
                                        MsgConstants.DEVICE_TYPE_ANDROID, title, forestkeeperIdList,
                                        new AliPushContentPojo(NoticeTypeConstants.NOTICE_TYPE_CAMERA_FIND_FIRE,
                                                JSON.toJSONString(content))));
                        if (ObjectUtil.isNull(pushResponse)) {
                            throw new Exception("阿里云短信通知推送失败!");
                        } else {
                            log.info("阿里推送消息{}", JSONUtil.toJsonStr(pushResponse));
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                    //查询值守人员手机号
                    List<String> mobileList = sysUsers.stream()
                            .filter(e -> StringUtils.isNotEmpty(e.getMobile()))
                            .map(SysUser::getMobile).collect(Collectors.toList());
                    //todo 发送短信给值守人员  xxxx视频监控发现了xx地址的火情，请前往判别
                    if (CollUtil.isNotEmpty(mobileList)) {
                        try {
                            msgService.pushFireAlarmConfirmSms(mobileList, commCameraInfo.getCameraName(), commCameraInfo.getAreaCode());
                        } catch (Exception e) {
                            log.error("火情短信推送失败:[{}]", e.getMessage());
                        }

                    }

                    //查询值守人员ID集合
                    List<Long> idList = sysUsers.stream().filter(e -> e.getId() != null).map(SysUser::getId).collect(
                            Collectors.toList());
                    //TODO 记录消息推送日志
                    for (Long id : idList) {
                        CommMsgCenterLog log = new CommMsgCenterLog(content, "6", new Date(), "1", commFireAlarm.getFinderName(), title, id);
                        commMsgCenterLogDao.insert(log);
                    }
                }
                //监控发现火情推送
                try {
                    final DataReturn dataReturn = communicateFeignClient.sendMsg(new SendMessageDTO("WEB", JSON.toJSONString(DataReturn.ok(MsgIdentificationConstants.CAMERA_FIND_FIRE, null))));
                    if (ObjectUtil.isNull(dataReturn)) {
                        throw new Exception("微服务调用推送websocket失败");
                    }
                    if (StrUtil.equals(dataReturn.getCode(), ResultCode.SUCCESS.getCode())) {
                        log.info("websocket推送火情成功!");
                    } else {
                        throw new Exception(StrUtil.format("code:[{}],errMsg:[{}]", dataReturn.getCode(), dataReturn.getErrorMsg()));
                    }
                } catch (Exception e) {
                    log.error("websocket 推送火情失败，原因是:[{}]", e.getMessage());
                }

            } else {
                //来源为7是防火管理员，防火管理员上报的真实火情的业务逻辑处理（推送web通知，发送短信，推送app通知）
                if ("7".equals(commFireAlarm.getResource()) && "3".equals(commFireAlarm.getStatus()) && "true".equals(enablePushFireSms)) {

                    // 给防火管理员发送预警短信
                    if (StringUtils.isNotBlank(commFireAlarm.getDistrictName()) && "true".equals(enablePushFireSms)) {
                        //真实火情推送人员手机号集合
                        List<String> pushRealFireMobileList = new ArrayList<>();
                        //防火管理员手机号集合
                        List<String> fireMangerMobileList = fireAdminService.fireMangerMobileList();
                        if (fireMangerMobileList != null && fireMangerMobileList.size() > 0) {
                            //防火管理员手机号集合添加到真是火情推送人员手机集合
                            pushRealFireMobileList.addAll(fireMangerMobileList);
                        }
                        //查询火情报警消息提醒手机号列表
                        try {
//                            DataReturn dataReturn = operationFeignClient.mobileListByType("4");
//                            if (StrUtil.equals(dataReturn.getCode(), ResultCode.SUCCESS.getCode()) && ObjectUtil.isNotNull(dataReturn.getData())) {
//                                //系统管理模块配置的“火情报警消息提醒”中的人员手机号集合添加到真是火情推送人员手机集合
//                                pushRealFireMobileList.addAll((List<String>) dataReturn.getData());
//                            }
                            //todo 更正真实火情推送模版业务逻辑
                            smsPushUriPubFacadeService.sendSms(commFireAlarm.getId(), pushRealFireMobileList, 1);
                        } catch (Exception e) {
                            log.error("获得手机号类型为4的短信推送失败,原因[{}]", e.getMessage());
                        }
                        List<String> fireMangerIdList = fireAdminService.fireMangerIdList();
                        String content = commFireAlarm.getDistrictName() + "地址发现了真实火情,请及时组织扑火工作";
                        String title = "火情报警";
                        try {
                            final PushResponse pushResponse = AliyunPushMessageUtils.customizeAdvancedPush(new AliPushMessagePojo(MsgConstants.TARGET_ACCOUNT, MsgConstants.PUSH_TYPE_MESSAGE, MsgConstants.DEVICE_TYPE_ANDROID, title, fireMangerIdList,
                                    new AliPushContentPojo(NoticeTypeConstants.NOTICE_TYPE_NORMAL, JSON.toJSONString(content))));
                            if (ObjectUtil.isNull(pushResponse)) {
                                throw new Exception("阿里云短信通知推送失败!");
                            } else {
                                log.info("阿里推送消息{}", JSONUtil.toJsonStr(pushResponse));
                            }
                        } catch (Exception e) {
                            log.error(e.getMessage());
                        }
                        fireMangerIdList.forEach(e -> {
                            CommMsgCenterLog log = new CommMsgCenterLog(content, "4", new Date(), "1", commFireAlarm.getFinderName(), title, Long.parseLong(e));
                            commMsgCenterLogDao.insert(log);
                        });
                         /* List<String> list = fireAdminService.fireMangerIdList();
                    String content = commFireAlarm.getDistrictName() + "发现了真实火情,请及时组织扑火工作";
                    String title = "发现真实火情";
                    AliyunPushMessageUtils.customizeAdvancedPush(new AliPushMessagePojo(MsgConstants.TARGET_ACCOUNT, MsgConstants.PUSH_TYPE_MESSAGE, MsgConstants.DEVICE_TYPE_ANDROID, title, list,
                            new AliPushContentPojo(NoticeTypeConstants.NOTICE_TYPE_NORMAL, JSON.toJSONString(content))));
                    list.forEach(e -> {
                        CommMsgCenterLog log = new CommMsgCenterLog(content, "4", new Date(), "1", userInfo.getRealName(), title, Long.parseLong(e));
                        commMsgCenterLogDao.insert(log);
                    });*/
                    }
                    try {
                        //其他来源上报火情推送
                        final DataReturn dataReturn = communicateFeignClient.sendMsg(new SendMessageDTO("WEB", JSON.toJSONString(DataReturn.ok(MsgIdentificationConstants.FIRE_ALARM, null))));
                        if (ObjectUtil.isNull(dataReturn)) {
                            throw new Exception("微服务调用推送websocket失败");
                        }
                        if (StrUtil.equals(dataReturn.getCode(), ResultCode.SUCCESS.getCode())) {
                            log.info("websocket推送火情成功!");
                        } else {
                            throw new Exception(StrUtil.format("code:[{}],errMsg:[{}]", dataReturn.getCode(), dataReturn.getErrorMsg()));
                        }
                    } catch (Exception e) {
                        log.error("websocket 推送火情失败，原因是:[{}]", e.getMessage());
                    }

                } else {
                    try {
                        //防火管理员通知以及短信疑似火情提醒
                        fireManagerNoticeAndMessage(commFireAlarm);
                        //其他来源上报火情推送
                        final DataReturn dataReturn = communicateFeignClient.sendMsg(new SendMessageDTO("WEB", JSON.toJSONString(DataReturn.ok(MsgIdentificationConstants.FIRE_ALARM, null))));
                        if (ObjectUtil.isNull(dataReturn)) {
                            throw new Exception("微服务调用推送websocket失败");
                        }
                        if (StrUtil.equals(dataReturn.getCode(), ResultCode.SUCCESS.getCode())) {
                            log.info("websocket推送火情成功!");
                        } else {
                            throw new Exception(StrUtil.format("code:[{}],errMsg:[{}]", dataReturn.getCode(), dataReturn.getErrorMsg()));
                        }
                    } catch (Exception e) {
                        log.error("websocket 推送火情失败，原因是:[{}]", e.getMessage());
                    }
                }
            }
        }

    }


    /**
     * 校验火情是否已有上报记录
     *
     * @param resource  来源
     * @param longitude 经度
     * @param latitude  纬度
     * @return true 已有上报记录
     */
    private void verifySameFire(List<String> resource, String longitude, String latitude) {
        //校验逻辑
        //相同来源火情校验
        List<CommFireAlarm> list = commFireAlarmDao.querySameSourceUnCompleteDisposalFire(resource);
        if (list != null && list.size() != 0) {
            List<CommFireAlarm> unCompleteDisposalFire = list.stream().filter(
                    e -> {
                        double distanceMeter = GeoUtils.GetDistanceTwo(Double.parseDouble(longitude), Double.parseDouble(latitude), Double.parseDouble(e.getLongitude()), Double.parseDouble(e.getLatitude()));
                        return distanceMeter < Double.parseDouble(limitDistance);
                    }
            ).collect(Collectors.toList());
            if (unCompleteDisposalFire.size() != 0) {
                //有相同来源数据
                throw new ForestBaseException(ResultCode.OPERATE_ERROR.getCode(), "该火情已有上报记录！");
            }
        }
        //不同来源火情校验
        list = commFireAlarmDao.queryNotSameSourceUnCompleteDisposalFire(resource);
        if (list != null && list.size() != 0) {
            List<CommFireAlarm> unCompleteDisposalFire = list.stream().filter(
                    e -> {
                        double distanceMeter = GeoUtils.GetDistanceTwo(Double.parseDouble(longitude), Double.parseDouble(latitude), Double.parseDouble(e.getLongitude()), Double.parseDouble(e.getLatitude()));
                        return distanceMeter < Double.parseDouble(limitDistance);
                    }
            ).collect(Collectors.toList());
            Set<String> set = new HashSet<>(list.size());
            if (unCompleteDisposalFire.size() > 1) {
                unCompleteDisposalFire.forEach(a -> {
                    String source = a.getResource();
                    set.add(source);
                });
            }
            if (set.size() > 2) {
                //来源已有2个，不允许新增
                throw new ForestBaseException(ResultCode.OPERATE_ERROR.getCode(), "该火情已有上报记录！");
            } else {
                //来源只有1个，可以新增
            }
        }
    }

    /**
     * 插入火情天气关联表数据
     *
     * @param fireId
     */
    private void insertWeatherInfo(Long fireId) {
        String weatherInfo = RedisUtils.get(RedisKeyConstant.ONE_DAY_WEATHER);
        DailyWeather dailyWeather;
        if (weatherInfo == null) {
            dailyWeather = weatherService.getOneDayWeather(address, 1, 5);
            RedisUtils.getAndSetWithExpire(RedisKeyConstant.ONE_DAY_WEATHER, JSON.toJSONString(dailyWeather), 60 * 60 * 24);
        } else {
            dailyWeather = JSONObject.parseObject(weatherInfo, DailyWeather.class);
        }
        FireWeatherInfo fireWeatherInfo = FireWeatherInfo.builder().fireId(fireId).textDay(dailyWeather.getText_day()).humidity(dailyWeather.getHumidity()).high(dailyWeather.getHigh())
                .low(dailyWeather.getLow()).windDirection(dailyWeather.getWind_direction()).windScale(dailyWeather.getWind_scale()).windSpeed(String.format("%.4f", Double.parseDouble(dailyWeather.getWind_speed()) * 0.2778))
                .rainfall(dailyWeather.getRainfall()).build();
        fireWeatherInfoDao.insert(fireWeatherInfo);
    }

    /**
     * 火情数据插入业务主键表
     *
     * @param commFireAlarm
     */
    private void insertBusinessTable(CommFireAlarm commFireAlarm) {
        if (commFireAlarm.getDistrictCode() == null) {
            throw new ForestBaseException(ResultCode.OPERATE_ERROR.getCode(), "火情上报所在位置错误！");
        }
        //去掉村级行政区划
        String districtCode = geoQueryService.queryXiangByCun(commFireAlarm.getDistrictCode(), commFireAlarm.getDistrictCode().length());
        if (districtCode == null) {
            throw new ForestBaseException(ResultCode.OPERATE_ERROR.getCode(), "火情上报所在位置错误！");
        }
        //火情信息插入业务主键表
        BusinessTable businessTable = new BusinessTable();
        businessTable.setBusinessKey(String.valueOf(commFireAlarm.getId()));
        businessTable.setDistrictCode(districtCode);
        businessTable.setDistrictLength(String.valueOf(districtCode.length()));
        businessTableDao.insertSelective(businessTable);
    }


    /**
     * 火情处置
     *
     * @param disposalProcessDTO
     */
//    private void disposalProcess(DisposalProcessDTO disposalProcessDTO) {
//        //检查是否有权限处置
//        //在现有业务逻辑下，可以查看的火情就是可以处置，所以下行代码注释掉
////        this.checkAuthority(disposalProcessDTO.getDistrictCode(), disposalProcessDTO.getBusinessKey());
//        //修改业务主键表数据
//        this.changeBusinessTable(disposalProcessDTO);
//    }

    /**
     * 检查是否有权限处置火情
     *
     * @param districtCode
     * @param businessKey
     */
    private void checkAuthority(String districtCode, String businessKey) {
        // excludeDistrict配置行政区划 可以处置所有地区火情
//        if (excludeDistrict.equals(districtCode)) {
        if (fireExcludeProp.getExcludeDistrict().contains(districtCode)) {
            return;
        }
        if (districtCode == null) {
            throw new ForestBaseException(ResultCode.OPERATE_ERROR.getCode(), "无权限处置该火情！");
        }

//        Map data = businessTableDao.queryByBusinessKey(businessKey);
//        if(ObjectUtil.isEmpty(data)){
//            throw new ForestBaseException(ResultCode.OPERATE_ERROR.getCode(), "无权限处置该火情！");
//        }
//        String code = (String) data.get("district_code");
//        if (code == null || businessKey == null) {
//            throw new ForestBaseException(ResultCode.OPERATE_ERROR.getCode(), "无权限处置该火情！");
//        }
//        if (code.indexOf(districtCode) != 0) {
////        if (code.indexOf(districtCode) == 0) {
//            throw new ForestBaseException(ResultCode.OPERATE_ERROR.getCode(), "无权限处置该火情！");
//        }
    }

    /**
     * 处置完成修改业务主键表数据
     *
     * @param disposalProcessDTO
     */
//    private void changeBusinessTable(DisposalProcessDTO disposalProcessDTO) {
//        String districtCode = disposalProcessDTO.getDistrictCode();
//        Map data = businessTableDao.queryByBusinessKey(disposalProcessDTO.getBusinessKey());
//        String businessKey = (String) data.get("business_key");
////        Integer id = (Integer) data.get("id");
//        String idStr = data.get("id").toString();
//        Integer id = Integer.valueOf(idStr);
//        if (disposalProcessDTO.getCapable() == 0) {
//            BusinessTable businessTable = new BusinessTable();
//            businessTable.setId(id);
//            businessTable.setBusinessKey(businessKey);
//            businessTable.setDistrictCode(geoQueryService.queryXianByXiang(districtCode));
//            businessTableDao.updateByPrimaryKeySelective(businessTable);
//        } else if (disposalProcessDTO.getCapable() == 1) {
//            businessTableDao.deleteByPrimaryKey(id);
//        }
//    }

    /**
     * 获取个人所在单位行政区划
     *
     * @return
     */
    private String getRegionCode() {
        Long id = JwtTokenUtils.getId();
        return id == null ? "" : userInfoService.getUserInfo(id).getAreaCode();
    }

    @Override
  //  @CacheEvict(value = {"firecommand:firealarm:queryUnFinishFireNum","firecommand:firealarm:queryLeftFireInfoOrderByTimeAndStatus","firecommand:firealarm:queryLeftFireInfo","firecommand:fire:queryAllFireByCondition","firecommand:fire:queryById","firecommand:fire:queryUnfinishedFireByDay"},allEntries = true)
    public void setAsRepeatedFire(Long sourceFireId, Long repeatFireId, HttpServletRequest httpServletRequest) {
        //执行合并逻辑
        executeSetRepeated(sourceFireId, repeatFireId, httpServletRequest);
    }

    /**
     * 执行合并逻辑
     *
     * @param sourceFireId       源火情id
     * @param repeatFireId       待合并火情id
     * @param httpServletRequest
     */
    private void executeSetRepeated(Long sourceFireId, Long repeatFireId, HttpServletRequest httpServletRequest) {
        CommFireAlarm sourceCommFireAlarm = commFireAlarmDao.selectByPrimaryKey(sourceFireId);
        CommFireAlarm repeatCommFireAlarm = commFireAlarmDao.selectByPrimaryKey(repeatFireId);
        //字段合并 火情状态以原火情状态为准
//        BeanUtils.copyProperties(repeatCommFireAlarm, sourceCommFireAlarm, "id", "status", "imageUrl");
        //多媒体资源进行合并
        /*String sourceImageUrl = sourceCommFireAlarm.getImageUrl();
        String repeatImageUrl = repeatCommFireAlarm.getImageUrl();
        List<String> list;
        if (repeatImageUrl != null) {
            List<String> repeatList = JSON.parseArray(repeatImageUrl, String.class);
            if (sourceImageUrl != null) {
                List<String> sourceList = JSON.parseArray(sourceImageUrl, String.class);
                list = new ArrayList<>(sourceList.size() + repeatList.size());
                list.addAll(sourceList);
                list.addAll(repeatList);
            } else {
                list = new ArrayList<>(repeatList.size());
                list.addAll(repeatList);
            }
            sourceCommFireAlarm.setImageUrl(JSON.toJSONString(list));
        }
        commFireAlarmDao.updateByPrimaryKeySelective(sourceCommFireAlarm);*/
//        repeatCommFireAlarm.setOriginFireId(sourceFireId);
        sourceCommFireAlarm.setOriginFireId(repeatFireId);
        //修改被合并火情的处置状态
//        repeatCommFireAlarm.setStatus(sourceCommFireAlarm.getStatus());
        sourceCommFireAlarm.setStatus(repeatCommFireAlarm.getStatus());
        sourceCommFireAlarm.setConfirmId(repeatCommFireAlarm.getConfirmId());
        sourceCommFireAlarm.setConfirmName(repeatCommFireAlarm.getConfirmName());
        sourceCommFireAlarm.setConfirmUnit(repeatCommFireAlarm.getConfirmUnit());
        sourceCommFireAlarm.setConfirmTime(repeatCommFireAlarm.getConfirmTime());
        sourceCommFireAlarm.setManagementId(repeatCommFireAlarm.getManagementId());
        sourceCommFireAlarm.setManagementTime(repeatCommFireAlarm.getManagementTime());
        sourceCommFireAlarm.setFinishId(repeatCommFireAlarm.getFinishId());
        sourceCommFireAlarm.setFinishTime(repeatCommFireAlarm.getFinishTime());
        //TODO 暂时不做重复火情的删除操作
//        repeatCommFireAlarm.setHasDelete(1);
        commFireAlarmDao.updateByPrimaryKeySelective(sourceCommFireAlarm);
//        Map map = businessTableDao.queryByBusinessKey(String.valueOf(repeatFireId));
//        if (map != null) {
//            //结束实例流程
//            DisposalProcessDTO disposalProcessDTO = new DisposalProcessDTO();
//            String districtCode = this.getRegionCode();
//            disposalProcessDTO.setCapable(1);
//            disposalProcessDTO.setDistrictCode(districtCode);
////            disposalProcessDTO.setBusinessKey(String.valueOf(repeatFireId));
//            disposalProcessDTO.setBusinessKey(String.valueOf(sourceFireId));
//            this.disposalProcess(disposalProcessDTO);
//        } else {
//            throw new ForestBaseException(ResultCode.OPERATE_ERROR.getCode(), "该火情处理流程不存在！");
//        }
    }

    @Override
   // @CacheEvict(value = {"firecommand:firealarm:queryUnFinishFireNum","firecommand:firealarm:queryLeftFireInfoOrderByTimeAndStatus","firecommand:firealarm:queryLeftFireInfo","firecommand:fire:queryAllFireByCondition","firecommand:fire:queryById","firecommand:fire:queryUnfinishedFireByDay","firecommand:resoure:selectFireAndEventCountByDistrictCode","firecommand:firealarm:selectFireCountBySourceByDistrictCode"},allEntries = true)
    public void confirmFire(Long fireId, String confirmType, String description, String mediaUrl, String faketype, HttpServletRequest
            httpServletRequest) {
//        String name = JwtTokenUtils.getRealName();
        Long userId = JwtTokenUtils.getId();
        String districtCode = this.getRegionCode();
        this.checkAuthority(districtCode, String.valueOf(fireId));
        if (websocketPushMsgLogDao.queryHasRead(1, fireId) == 0) {
            WebsocketPushMsgLog websocketPushMsgLog = new WebsocketPushMsgLog();
            websocketPushMsgLog.setUserId(userId);
            websocketPushMsgLog.setEventId(fireId);
            websocketPushMsgLog.setEventType(1);
            websocketPushMsgLogDao.insertSelective(websocketPushMsgLog);
        }
        // app确认火情上传文件
        if (!StringUtils.isEmpty(mediaUrl)) {
            commFireAlarmDao.updateFiles(mediaUrl, fireId);
        }
        //查询原火情id为该火情的火情
        List<Long> fireAlarmByOrginIdList = commFireAlarmDao.queryAllFireAlarmByOrginId(fireId);
        //根据火情ID查询火情行政区划
        String fireAlarmDistrictCode = commFireAlarmDao.queryDistrictCodeById(fireId);
        CommFireAlarm commFireAlarm = commFireAlarmDao.selectByPrimaryKey(fireId);
        switch (confirmType) {
            case "1":
                //1确认火情
                commFireAlarmDao.updateStatus(fireId, "3", userId, new Date(), description);
                commFireAlarmDao.updateJudgmentType(fireId, 1);
                //修改火情状态
                updateStatusByFireIdList(fireAlarmByOrginIdList, userId, "3");
                //推送状态修改信息给web端
                pushFireStatusForWeb(fireAlarmDistrictCode, "3");

                //给乡镇、区县级防火管理员发送短信
                List<SysUser> sysUsers = sysUserDAO.selectByCondition(null, null, fireAlarmDistrictCode, false,
                        RoleCodeConstants.ROLE_CODE_FIRE_MANAGER_ID, null, null, Integer.MAX_VALUE, 0);
                List<SysUser> sysUsers2 = sysUserDAO.selectByCondition(null, null,
                        fireAlarmDistrictCode.substring(0, 6), false,
                        RoleCodeConstants.ROLE_CODE_FIRE_MANAGER_ID, null, null, Integer.MAX_VALUE, 0);
                if (CollectionUtil.isNotEmpty(sysUsers2)) {
                    sysUsers.addAll(sysUsers2);
                }
                List<String> mobiles = sysUsers.stream().filter(
                        vo -> ObjectUtil.isNotNull(vo.getId()) && StrUtil.isNotEmpty(vo.getMobile()))
                        .map(SysUser::getMobile)
                        .distinct()
                        .collect(Collectors.toList());
                if (CollUtil.isEmpty(mobiles)) {
                    log.error("暂无人员需要收到短信推送");
                } else {
                    try {
                        SmsUtils.sendContent(mobiles, "SMS_232160324",
                                new SmsRealDto().setAddress(commFireAlarm.getDetailAddress()));
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("短信发送失败：{}", e.getMessage());
                    }
                }
                break;
            case "2":
                //2确认误报
                commFireAlarmDao.comfirmFakeFire(fireId, "6", description, faketype, userId, new Date());
                //修改火情状态
                updateStatusByFireIdList(fireAlarmByOrginIdList, userId, "6");
                //推送状态修改信息给web端
                pushFireStatusForWeb(fireAlarmDistrictCode, "6");
//                Map map = businessTableDao.queryByBusinessKey(String.valueOf(fireId));
//                if (map != null) {
//                    //结束实例流程
//                    DisposalProcessDTO disposalProcessDTO = new DisposalProcessDTO();
//                    disposalProcessDTO.setCapable(1);
//                    disposalProcessDTO.setDistrictCode(districtCode);
//                    disposalProcessDTO.setBusinessKey(String.valueOf(fireId));
//                    this.disposalProcess(disposalProcessDTO);
//                } else {
//                    throw new ForestBaseException(ResultCode.OPERATE_ERROR.getCode(), "该火情处理流程不存在！");
//                }
                break;
            case "3":
                //3设为应急演练
                commFireAlarmDao.changeAction(fireId, "2");
                commFireAlarmDao.updateStatus(fireId, "3", userId, new Date(), description);
                //修改火情状态
                updateStatusByFireIdList(fireAlarmByOrginIdList,userId,"3");
                //推送状态修改信息给web端
                pushFireStatusForWeb(fireAlarmDistrictCode,"3");
                //设为应急演练
                if(ObjectUtil.isNotEmpty(fireAlarmByOrginIdList)){
                    //修改原火情是当前火情的其他火情的状态，进行同步操作
                    for (Long fireAlarmByOrginId :
                            fireAlarmByOrginIdList) {
                        commFireAlarmDao.changeAction(fireAlarmByOrginId,"2");
                    }
                }
                break;
        }
    }

    private void pushFireStatusForWeb(String fireAlarmDistrictCode,String status) {
        try {
            //查询行政区划及以上防火管理员的ID集合
            final List<String> fireMangerIdList = CollUtil.<String>newArrayList();
            if (fireAlarmDistrictCode != null && fireAlarmDistrictCode.length() >= 9) {
                fireMangerIdList.addAll(fireAdminService.fireMangerIdListByDistrictCode(fireAlarmDistrictCode.substring(0, 9)));
            } else {
                fireMangerIdList.addAll(fireAdminService.fireMangerIdList());
            }
            if (fireMangerIdList != null && fireMangerIdList.size() > 0) {
                communicateFeignClient.sendMsg(new SendMessageDTO("WEBWITHINUSERID", Convert.toStrArray(fireMangerIdList), JSON.toJSONString(DataReturn.ok(MsgIdentificationConstants.FIRE_STATUS_UPDATE, status))));
            }

        }catch (Exception e){
            log.error("修改火情状态：{},推送失败",status);
        }
    }

    private void updateStatusByFireIdList(List<Long> fireAlarmIdList,Long userId,String status){
        if(ObjectUtil.isNotEmpty(fireAlarmIdList)){
            //修改原火情是当前火情的其他火情的状态，进行同步操作
            for (Long fireAlarmByOrginId :
                    fireAlarmIdList) {
                commFireAlarmDao.updateStatus(fireAlarmByOrginId,status, userId, new Date(), null);
            }
        }
    }


    @Override
    public void reportToSuperior(Long fireId, HttpServletRequest httpServletRequest) {
        Long hasReport = fireReportSuperiorLogDao.queryHasReport(fireId);
        if (hasReport > 0) {
            throw new ForestBaseException("该火情已上报！");
        }
      //  Map map = businessTableDao.queryByBusinessKey(String.valueOf(fireId));
    //    if (map != null) {
//            //上报实例流程
//            DisposalProcessDTO disposalProcessDTO = new DisposalProcessDTO();
            String name = JwtTokenUtils.getRealName();
            Long id = JwtTokenUtils.getId();
//            // 获取用户单位
        MicroSysUserAllInfoVo userInfo = userInfoService.getUserInfo(id);
        String unit = userInfo == null ? null : userInfo.getDeptName();
//            String districtCode = this.getRegionCode();
//            disposalProcessDTO.setCapable(0);
//            disposalProcessDTO.setDistrictCode(districtCode);
//            disposalProcessDTO.setBusinessKey(String.valueOf(fireId));
//            this.disposalProcess(disposalProcessDTO);
            CommFireAlarm commFireAlarm = commFireAlarmDao.selectByPrimaryKey(fireId);
            FireReportSuperiorLog fireReportSuperiorLog = new FireReportSuperiorLog();
            fireReportSuperiorLog.setFireId(fireId);
            fireReportSuperiorLog.setReportPersonId(id);
            fireReportSuperiorLog.setReportPersonName(name);
            fireReportSuperiorLog.setReportPersonUnit(unit);
            fireReportSuperiorLog.setFireStatus(Integer.valueOf(commFireAlarm.getStatus()));
            fireReportSuperiorLog.setReportTime(new Date());
            fireReportSuperiorLogDao.insertSelective(fireReportSuperiorLog);
            //推送给web端
            communicateFeignClient.sendMsg(new SendMessageDTO("web", JSON.toJSONString(DataReturn.ok(MsgIdentificationConstants.FIRE_REPORT, null))));
//        } else {
//            throw new ForestBaseException(ResultCode.OPERATE_ERROR.getCode(), "该火情处理流程不存在！");
//        }
    }

    @Override
   // @CacheEvict(value = {"firecommand:firealarm:queryLeftFireInfoOrderByTimeAndStatus","firecommand:firealarm:queryLeftFireInfo","firecommand:fire:queryAllFireByCondition","firecommand:fire:queryById","firecommand:fire:queryUnfinishedFireByDay"},allEntries = true)
    public void updateFireRegionalInfo(CommFireAlarm commFireAlarm, HttpServletRequest httpServletRequest) {
        //TODO 查询原火情经纬度
        CommFireAlarm retCommFireAlarm = commFireAlarmDao.selectByPrimaryKey(commFireAlarm.getId());
        //记录火情位置纠偏处置流程
        FirePositionCorrection recordScene =new FirePositionCorrection();
        recordScene.setFireId(commFireAlarm.getId());
        //设置原火情经纬度
        recordScene.setOldlongitude(retCommFireAlarm.getLongitude());
        recordScene.setOldlatitude(retCommFireAlarm.getLatitude());
        //修改火情位置
        commFireAlarmDao.updateByPrimaryKeySelective(commFireAlarm);
        //获取当前用户
        Long id = JwtTokenUtils.getId();
        MicroSysUserAllInfoVo userInfo = userInfoService.getUserInfo(id);

        //设置经度信息
        if(StrUtil.isNotEmpty(retCommFireAlarm.getLongitude())) {
            recordScene.setLongitude(retCommFireAlarm.getLongitude());
        }
        //设置经度信息
        if(StrUtil.isNotEmpty(retCommFireAlarm.getLatitude())) {
            recordScene.setLatitude(retCommFireAlarm.getLatitude());
        }
        fireDisposeService.processDisposeInfo(recordScene, userInfo);
    }


    /**
     * 修改火情状态
     * 流程：
     * 待接警（PendingAlarm） --> 待核实（ToBeVerified） --> 待处置（PendingDisposal） --> 处置中（UnderDisposal） --> 已处置（HasDisposed）
     *
     * @param fireId             火情id
     * @param status             火情状态
     * @param httpServletRequest
     * @return 是否执行成功
     */
    @Override
   // @CacheEvict(value = {"firecommand:firealarm:queryUnFinishFireNum","firecommand:firealarm:queryLeftFireInfoOrderByTimeAndStatus","firecommand:firealarm:queryLeftFireInfo","firecommand:fire:queryAllFireByCondition","firecommand:fire:queryById","firecommand:fire:queryUnfinishedFireByDay"},allEntries = true)
    public void changeFireStatus(Long fireId, String status, HttpServletRequest httpServletRequest) {
        Long userId = JwtTokenUtils.getId();
        String districtCode = this.getRegionCode();

        //判断是否有权限处置
//        this.checkAuthority(districtCode, String.valueOf(fireId));

        if ("2".equals(status)) {
            //待核实,消息推送记录表插入数据
            if (websocketPushMsgLogDao.queryHasRead(1, fireId) == 0) {
                WebsocketPushMsgLog websocketPushMsgLog = new WebsocketPushMsgLog();
                websocketPushMsgLog.setUserId(Long.valueOf(userId));
                websocketPushMsgLog.setEventId(fireId);
                websocketPushMsgLog.setEventType(1);
                websocketPushMsgLogDao.insertSelective(websocketPushMsgLog);
            }
            commFireAlarmDao.updateReceiveInfo(status, fireId, userId, new Date());
        } else if ("4".equals(status)) {
            //处置中
            commFireAlarmDao.updateManagementInfo(status, fireId, userId, new Date());
        } else if ("5".equals(status)) {
            //填充处置中信息
            CommFireAlarm commFireAlarm = fireQueryService.queryById(fireId);
            if (commFireAlarm.getManagementId() == null) {
                MicroSysUserAllInfoVo userInfo = userInfoService.getUserInfo(JwtTokenUtils.getId());
                RecordScene recordScene = new ProcessFire();
                recordScene.setFireId(fireId);
                fireDisposeService.processDisposeInfo(recordScene, userInfo);

                commFireAlarmDao.updateManagementInfo(status, fireId, userId, new Date());
            }

            //已完成处置
            // 判断是否有音视频通话或者联动标绘
            if (communicateRecordService.checkHasMeetingByFireId(fireId)
                    || cadPlotRoomService.searchCountByFireAlarmId(fireId, "1") > 0) {
                throw new ForestBaseException(ResultCode.HAS_COMMAND_AND_CONTROL.getCode(), "当前火情正在进行指挥调度");
            }

            commFireAlarmDao.updateFinishInfo(status, fireId, userId, new Date());
        }
    }

    @Override
    //@CacheEvict(value = {"firecommand:firealarm:queryUnFinishFireNum","firecommand:firealarm:queryLeftFireInfoOrderByTimeAndStatus","firecommand:firealarm:queryLeftFireInfo","firecommand:fire:queryAllFireByCondition","firecommand:fire:queryById","firecommand:fire:queryUnfinishedFireByDay","firecommand:resoure:selectFireAndEventCountByDistrictCode","firecommand:firealarm:selectFireCountBySourceByDistrictCode"},allEntries = true)
    public void judgmentCameraFindFire(Long fireId, Integer fireJudgmentType) throws Exception {
        Long hasJudgment = commFireAlarmDao.hasJudgment(fireId);
        if (hasJudgment != 0L) {
            throw new ForestBaseException("该火情已判别！");
        } else {
            CommFireAlarm commFireAlarm = fireQueryService.queryById(fireId);
            commFireAlarm.setFireJudgmentType(fireJudgmentType);
            if (StringUtil.isNotEmpty(commFireAlarm.getImageUrl())) {
                //筛选出可见光的图片
                List<String> imageUrlList = JSON.parseArray(commFireAlarm.getImageUrl(), String.class);
                String newUrl = null;
                if (fireJudgmentType == 1) {
                    //真实火情 移动图片到 realFire文件夹
//                    newUrl = MinioUtils.removeToNewFolder("['" + imageUrlList.get(1) + "']", MinioConstants.BUCKET_FORESTRY_NAME, MinioConstants.BUCKET_REAL_FIRE_SUFFIX_NAME);
                    newUrl = MinioUtils.removeToNewFolder(JSON.toJSONString(imageUrlList), MinioConstants.BUCKET_FORESTRY_NAME, MinioConstants.BUCKET_REAL_FIRE_SUFFIX_NAME);
                } else if (fireJudgmentType == 2) {
                    //疑似火情 移动图片到 suspectFire文件夹
//                    newUrl = MinioUtils.removeToNewFolder("['" + imageUrlList.get(1) + "']", MinioConstants.BUCKET_FORESTRY_NAME, MinioConstants.BUCKET_SUSPECT_FIRE_SUFFIX_NAME);
                    newUrl = MinioUtils.removeToNewFolder(JSON.toJSONString(imageUrlList), MinioConstants.BUCKET_FORESTRY_NAME, MinioConstants.BUCKET_SUSPECT_FIRE_SUFFIX_NAME);
                   /* communicateFeignClient.sendMsg(new SendMessageDTO("WEB", JSON.toJSONString(DataReturn.ok(MsgIdentificationConstants.FIRE_ALARM, null))));
                    //防火管理员通知以及短信疑似火情提醒
                    fireManagerNoticeAndMessage(commFireAlarm);*/
                } else if (fireJudgmentType == 3) {
                    //误报 移动图片到 fakeFire文件夹
//                    newUrl = MinioUtils.removeToNewFolder("['" + imageUrlList.get(1) + "']", MinioConstants.BUCKET_FORESTRY_NAME, MinioConstants.BUCKET_FAKE_FIRE_SUFFIX_NAME);
                    newUrl = MinioUtils.removeToNewFolder(JSON.toJSONString(imageUrlList), MinioConstants.BUCKET_FORESTRY_NAME, MinioConstants.BUCKET_FAKE_FIRE_SUFFIX_NAME);
                }
                commFireAlarm.setImageUrl(newUrl);
            }

            if (fireJudgmentType == 1 || fireJudgmentType == 2) {
                //防火管理员web通知
                DataReturn dataReturn = communicateFeignClient.sendMsg(new SendMessageDTO("WEB", JSON.toJSONString(DataReturn.ok(MsgIdentificationConstants.FIRE_ALARM, null))));
                log.info("websocket推送情况:[{}]",  JSONUtil.toJsonStr(dataReturn));
                //防火管理员通知以及短信疑似火情提醒，以及疑似火情的语音播报
                fireManagerNoticeAndMessage(commFireAlarm);
            }
            commFireAlarmDao.updateByPrimaryKey(commFireAlarm);
        }
    }

    private void fireManagerNoticeAndMessage(CommFireAlarm commFireAlarm) throws Exception {
        //疑似火情给防火管理员推送通知
        List<String> list=new ArrayList<>();
        if(commFireAlarm.getDistrictCode() !=null && commFireAlarm.getDistrictCode().length() >=9){
            list=fireAdminService.fireMangerIdListByDistrictCode(commFireAlarm.getDistrictCode().substring(0,9));
        }else {
            list = fireAdminService.fireMangerIdList();
        }
        //疑似火情给防火管理员推送通知
//        List<String> list = fireAdminService.fireMangerIdList();
        //标题
        String title = "";
        String content = "";

        if (ObjectUtil.isNotNull(commFireAlarm.getFireJudgmentType())) {
            //视频监控发现的火情
            if (commFireAlarm.getFireJudgmentType() == 1 || commFireAlarm.getFireJudgmentType() == 2) {
                content = commFireAlarm.getFinderName() + "视频监控发现了" + commFireAlarm.getDistrictName() + "地址的火情，请前往查看";
                title = "视频监控火情报警";
            }
        }

        //电话接警
        if ("6".equals(commFireAlarm.getResource())) {
            String realName = JwtTokenUtils.getRealName();
            content = "防火管理员" + realName + "通过电话接警上报" + commFireAlarm.getFinderName() + "发现了" + commFireAlarm.getDistrictName() + "地址的火情，请前往查看";
            title = "你有新的上报火情";
        }
        //防火管理员疑似火情
        if ("7".equals(commFireAlarm.getResource())) {
            content = "防火管理员" + commFireAlarm.getFinderName() + "发现了" + commFireAlarm.getDistrictName() + "地址的火情，请前往查看";
            title = "你有新的上报火情";
        }
        //护林员疑似火情
        if ("1".equals(commFireAlarm.getResource())) {
            content = "护林员" + commFireAlarm.getFinderName() + "给你上报了" + commFireAlarm.getDistrictName() + "地址的火情，请前往查看";
            title = "你有新的上报火情";
        }
        //飞手疑似火情
        if ("2".equals(commFireAlarm.getResource())) {
            content = "飞手" + commFireAlarm.getFinderName() + "给你上报了" + commFireAlarm.getDistrictName() + "地址的火情，请前往查看";
            title = "你有新的上报火情";
        }
        try {
            AliyunPushMessageUtils.customizeAdvancedPush(new AliPushMessagePojo(MsgConstants.TARGET_ACCOUNT, MsgConstants.PUSH_TYPE_MESSAGE, MsgConstants.DEVICE_TYPE_ANDROID, title, list,
                    new AliPushContentPojo(NoticeTypeConstants.NOTICE_TYPE_NORMAL, JSON.toJSONString(content))));
        } catch (Exception e) {
            log.error("调用阿里通知失败[{}]", e.getMessage());
        }
        String finalContent = content;
        String finalTitle = title;
        list.forEach(e -> {
            CommMsgCenterLog log = new CommMsgCenterLog(finalContent, "3", new Date(), "1", commFireAlarm.getFinderName(), finalTitle, Long.parseLong(e));
            commMsgCenterLogDao.insert(log);
        });
        //todo 更正疑似火情推送模版业务逻辑，疑似火情给防火管理员推送疑似火情短信
        //防火管理员手机号集合
        //防火管理员手机号集合
        List<String> fireMangerMobileList =new ArrayList<>();
        //根据行政区划查询防火管理员手机号集合（包含浦口区防火管理员）
        if(commFireAlarm.getDistrictCode() !=null && commFireAlarm.getDistrictCode().length() >=9){
            fireMangerMobileList=fireAdminService.fireMangerMobileListByDistrictCode(commFireAlarm.getDistrictCode().substring(0,9));
        }else {
            fireMangerMobileList = fireAdminService.fireMangerMobileList();
        }
//        List<String> fireMangerMobileList = fireAdminService.fireMangerMobileList();

        try{
            //短信推送接口
            boolean bool = smsPushUriPubFacadeService.sendSms(commFireAlarm.getId(), fireMangerMobileList, 2);
            if (!bool) {
                log.error("调用阿里发送短信失败失败");
            }
        }catch(Exception e){
            log.error(e.getMessage());
        }

        try {
            //TODO 推送给防火管理员疑似火情的语音提醒
            boolean voiceBool = voicePushFacadeService.pushVoice(commFireAlarm.getId(), fireMangerMobileList, 2);
            if (!voiceBool) {
                log.error("调用阿里发送语音失败");
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }

    }

    /**
     * 保存火情图片
     *
     * @param fireFiles 文件
     */
    @Override
    public void saveFireFiles(List<FileUploadLog> fireFiles) {
        Date now = new Date();
        fireFiles.forEach(log -> {
            log.setUploadTime(now);
            fileUploadLogService.add(log);
        });
    }

    @Override
    public void updateFireInfo(CommFireAlarm commFireAlarm) {
        commFireAlarmDao.updateByPrimaryKeySelective(commFireAlarm);
    }

}
